package com.ifast.sys.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.ifast.common.utils.Result;

import cn.hutool.core.annotation.AnnotationUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 表单放重复提交验证 url 完全相同 第二次不走controller 
 * @author ShiQiang
 * @date 2019年4月15日16:06:42
 */
@Slf4j
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) { 
			SameUrlData annotation = AnnotationUtil.getAnnotation(((HandlerMethod) handler).getMethod(), SameUrlData.class);
			if (annotation == null) {
				return true;
			}  
			if (!repeatDataValidator(request)){
				return true;
			}
			// 如果重复相同数据
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8"); 
			try(PrintWriter out = response.getWriter()) { 
				out.append(JSON.toJSONString(Result.build(Result.CODE_FAIL, "重复提交数据！")));
			} catch (IOException e) {
				log.error("重复数据返回值错误", e);
			}  
			return false;
		} else {
			return super.preHandle(request, response, handler);
		}
	}

	/**
	 * 验证同一个url数据是否相同提交 ,相同返回true
	 * 
	 * @param httpServletRequest
	 * @return
	 */
	public boolean repeatDataValidator(HttpServletRequest httpServletRequest) {
		String params = JSON.toJSONString(httpServletRequest.getParameterMap());
		String url = httpServletRequest.getRequestURI();
		Map<String, String> map = new HashMap<String, String>();
		map.put(url, params);
		String nowUrlParams = map.toString();//

		Object preUrlParams = httpServletRequest.getSession().getAttribute("repeatData");
		if (preUrlParams == null){
			// 如果上一个数据为null,表示还没有访问页面
			httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
			return false;
		} 
		// 否则，已经访问过页面
		if (preUrlParams.toString().equals(nowUrlParams))
			return true;// 如果上次url+数据和本次url+数据相同，则表示重复添加数据
		
		// 如果上次 url+数据 和本次url加数据不同，则不是重复提交
		httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
		return false; 
	}
}
